<template>
    <el-card shadow="always">
        {{studentSearch}}
        <!--条件查询表单-->
        <el-form :inline="true" :model="studentSearch" class="demo-form-inline" align="left">
            <el-form-item >
                <el-input v-model="studentSearch.sname" placeholder="学生姓名"></el-input>
            </el-form-item>
            <el-form-item >
                <el-input v-model="studentSearch.addr" placeholder="学生住址"></el-input>
            </el-form-item>
            <el-form-item >
                <el-select v-model="studentSearch.cid" placeholder="所在班级">
                    <el-option label="所有班级" value="0"></el-option>
                    <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="search" plain size="medium" icon="el-icon-search">查询</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="success" @click="addStud" plain size="medium" icon="el-icon-plus">添加</el-button>
            </el-form-item>
        </el-form>
        <!--1. 表格数据的展示-->
        <el-table
                :data="students"
                style="width: 100%">
            <el-table-column
                    label="学号"
                    prop="sid"
                    align="center"
                    width="180">
            </el-table-column>
            <el-table-column
                    label="姓名"
                    align="center"
                    prop="sname">
            </el-table-column>
            <el-table-column
                    label="性别"
                    align="center"
                    prop="sex">
            </el-table-column>
            <el-table-column
                    label="年龄"
                    align="center"
                    prop="age">
            </el-table-column>
            <el-table-column
                    label="住址"
                    align="center"
                    prop="addr">
            </el-table-column>
            <el-table-column
                    label="所在班级"
                    align="center"
                    prop="cname">
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            round
                            type="primary"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)">编辑
                    </el-button>
                    <el-button
                            size="mini"
                            round
                            icon="el-icon-delete"
                            type="danger"
                            @click="handleDelete(scope.$index, scope.row)">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--2. 分页导航-->
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="page"
                :page-sizes="[5, 10, 15, 20]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
        </el-pagination>

        <el-dialog :title="student.sid ? '修改学生' : '添加学生' " :visible.sync="dialogFormVisible" :close-on-click-modal="false" align="left">
            {{student}}
            <el-form :model="student" :rules="rules" ref="studentRuleForm">
                <el-form-item label="学生姓名" :label-width="formLabelWidth" prop="sname">
                    <el-input v-model="student.sname" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="学生性别" :label-width="formLabelWidth" prop="sex">
                    <el-radio v-model="student.sex" label="男">男</el-radio>
                    <el-radio v-model="student.sex" label="女">女</el-radio>
                </el-form-item>
                <el-form-item label="学生年龄" :label-width="formLabelWidth" prop="age">
                    <el-input v-model.number="student.age" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="学生住址" :label-width="formLabelWidth" prop="addr">
                    <el-input v-model="student.addr" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="所在班级" :label-width="formLabelWidth" prop="cid">
                    <el-select v-model="student.cid" placeholder="请选择所在班级">
                        <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="save()">保存学生</el-button>
            </div>
        </el-dialog>
    </el-card>


</template>

<script>
    import {findByPage,findStudents,search,save,delStud} from "@/api/student"
    import {findClasses} from "@/api/classes";

    export default {
        data() {
            //自定义验证规则
            let checkAge = (rule,value,callback) => {
                if(!value){
                     callback(new Error("年龄不能为空！"))
                }else if(!Number.isInteger(value)){
                     callback(new Error("年龄必须为数字！"))
                }else if(value > 200 || value < 1){
                     callback(new Error("年龄必须在1-200之间！"))
                }else{
                     callback()
                }
            }
            return {
                students: [],
                page:1,
                pageSize:5,
                total:100,
                studentSearch:{},
                classes:[],
                dialogFormVisible:false,        // 对话框的显示与隐藏属性
                formLabelWidth:'100px',         // 文本提示的宽度值
                student:{},                     // 添加的学生对象
                title: '',                      // 对话框标题

                //定义校验规则
                rules:{
                    sname:[
                        {required:true,message:"学生姓名不能为空！",trigger:'blur'}
                    ],
                    sex:[
                        {required:true,message:"必须选择性别！",trigger:'blur'}
                    ],
                    age:[
                        {validator:checkAge,trigger:'blur'}
                    ],
                    addr:[
                        {required:true,message:"学生住址不能为空！",trigger:'blur'}
                    ],
                    cid:[
                        {required:true,message:"必须选择班级！",trigger:'blur'}
                    ],
                }
            }
        },
        methods: {
            handleEdit(index, row) {        // index：点击行的索引 row：点击行的内容
                console.log(index, row);
                //1. 填充数据到表单中
                this.student = row
                //2. 修改对话框标题
                // this.title = "修改学生"
                //3. 打开对话框
                this.dialogFormVisible = true

            },
            // 删除学生
            handleDelete(index, row) {
                console.log(index, row);
                let _this = this
                this.$confirm(`是否真的要删除${row.sname}?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {         // 点“确定”按钮后触发
                    delStud(row.sid).then(({data}) => {
                        if(data.code === 0){
                            this.$message({
                                type: 'success',
                                message: data.msg,
                                onClose(){      // 刷新页面
                                    _this.search()
                                }
                            });
                        }
                    })

                }).catch(() => {      // 点“取消”按钮后触发
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            // 当每页大小改变时触发
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.pageSize = val
                // this.findByPage()
                this.search()
            },
            // 当当前页改变时触发
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.page = val
                // this.findByPage()
                this.search()
            },
            //1. 查询所有学生
            findStudents() {
                findStudents().then(({data})=>{
                    this.students = data
                })
            },
            //2. 分页查询学生
            findByPage(){
                findByPage(this.page,this.pageSize).then(({data}) => {
                    this.total = data.total
                    this.students = data.rows
                })
            },
            //3. 查询班级
            findClasses() {
                findClasses().then(({data}) => {
                    this.classes = data
                })
            },
            //4. 开始条件查询带分页
            search(){
                search(this.page,this.pageSize,this.studentSearch).then(({data}) => {
                    console.log("data:",data)
                    this.total = data.pr.total
                    this.students = data.pr.rows
                })
            },
            //5. 添加学生
            addStud(){
                //5.1 清空原来的数据
                this.student = {}
                //5.2 改造标题
                // this.title = "添加学生"
                //5.2 弹出对话框
                this.dialogFormVisible = true
            },
            //6. 保存学生（同时添加或修改）
            save(){
               //6.1 确定添加或修改的地址
                // update student set sname=?,sex=?,age=?,addr=?,cid=? where sid = ?
               let url = "/student?cmd=add"
               if(this.student.sid){
                   url = "/student?cmd=update"
               }
               this.$refs['studentRuleForm'].validate((valid) =>{
                   let _this = this
                   if(valid){       // 如果为true,代表所有的控件验证通过

                      save(url,this.student).then(({data}) => {
                          console.log(data)
                          if(data.code === 0){  //=== 即比较内容又比较类型
                              this.$message({
                                  message: data.msg,
                                  type: 'success',
                                  onClose(){  // 当消息框执行完成后，此回调将被执行
                                      _this.dialogFormVisible = false
                                      _this.search()
                                  }
                              });
                          }
                      })
                   }
               })
            }
        },
        created() {
            //1. 查询所有学生
            // this.findStudents()
            //2. 分页查询学生信息
            // this.findByPage()
            this.search()
            //3. 查询所有班级
            this.findClasses()
        }
    }
</script>

<style>
    .el-pagination{
        text-align: right;
        margin-top: 20px;
    }
</style>